import PageCommon from "@/components/PageCommon";

import { add_user, delete_user, edit_user, get_user_list } from "@/services/user";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ModalForm, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { Button, Form, message, Popconfirm, Space } from "antd";
import dayjs from "dayjs";
import { useRef, useState } from "react";

const userMap = {
  add: add_user,
  update: edit_user
};

const UseUserList = () => {
  const [form] = Form.useForm<Types.User.IUserInfo>();

  const actionRef = useRef<ActionType>();
  const [messageApi, contextHolder] = message.useMessage();
  const [openUserForm, setOpenUserForm] = useState(false);
  const [isNew, setIsNew] = useState(true);
  const [id, setID] = useState("");
  const columns: ProColumns<any>[] = [
    {
      title: "ID",
      dataIndex: "id"
    },
    {
      title: "Name",
      dataIndex: "username"
    },
    {
      title: "Tel",
      dataIndex: "tel"
    },
    {
      title: "remark",
      dataIndex: "remark",
      hideInSearch: true
    },
    {
      title: "CreatedAt",
      dataIndex: "created_at",
      hideInSearch: true,
      render: (_, record) => {
        return <span>{dayjs(record.created_at).format("YYYY-MM-DD HH:mm:ss")}</span>;
      }
    },
    {
      title: "UpdatedAt",
      dataIndex: "updated_at",
      hideInSearch: true,
      render: (_, record) => {
        return <span>{dayjs(record.updated_at).format("YYYY-MM-DD HH:mm:ss")}</span>;
      }
    },
    {
      title: "操作",
      dataIndex: "filter",
      hideInSearch: true,
      width: 100,
      fixed: "right",
      render: (_, record) => {
        return (
          <Space>
            <Button
              size="small"
              onClick={() => {
                setIsNew(false);
                form.setFieldsValue(record);
                setOpenUserForm(true);
                setID(record.id);
              }}
            >
              Edit
            </Button>

            <Popconfirm
              title="确定要删除？"
              onConfirm={async () => {
                let res = await delete_user(record.id);
                if (res.code === 0) {
                  messageApi.success("ok!");
                  actionRef.current?.reload();
                }
              }}
            >
              <Button type="primary" danger size="small">
                Delete
              </Button>
            </Popconfirm>
          </Space>
        );
      }
    }
  ];

  return (
    <PageCommon>
      {contextHolder}
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        request={async ({ current, pageSize, ...search }) => {
          let params = {
            page: current,
            page_size: pageSize,
            ...search
          };
          let resp = await get_user_list(params);
          return {
            total: resp.data.total,
            success: resp.code === 0,
            data: resp.data.list
          };
        }}
        columns={columns}
        toolbar={{
          settings: []
        }}
        headerTitle={[
          <Button
            type="primary"
            key={1}
            onClick={() => {
              setIsNew(true);
              setOpenUserForm(true);
            }}
          >
            User Add
          </Button>
        ]}
      />

      <ModalForm<Types.User.IUserInfo>
        open={openUserForm}
        title="User Add"
        form={form}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpenUserForm(false)
        }}
        onFinish={async (values) => {
          let params = values;

          if (!isNew) {
            params.id = Number(id);
          }

          const resp = await userMap[isNew ? "add" : "update"](values);

          if (resp?.code === 0) {
            message.success(`${isNew ? "新增" : "编辑"}成功`);
            actionRef.current?.reload();
            setOpenUserForm(false);
            return true;
          }
        }}
      >
        <ProFormText
          name="username"
          label="Name"
          rules={[{ required: true, message: "此项必填" }]}
        />

        {isNew ? (
          <ProFormText.Password
            name="password"
            label="Password"
            rules={[{ required: true, message: "此项必填" }]}
          />
        ) : null}

        <ProFormText name="tel" label="Tel" rules={[{ required: true, message: "此项必填" }]} />

        <ProFormTextArea label="remark" placeholder="" name="remark" />
      </ModalForm>
    </PageCommon>
  );
};

export default UseUserList;
